<?php
require "Zend/Session/Namespace.php";

class BaseController extends Zend_Controller_Action
{
    private $session_space = 'user78';
    public  $user_id;
    public  $openid;
    public  $nickname;
    public  $headimgurl;
    public  $is_login;
    function __construct(Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response, array $invokeArgs = array())
    {
        // 微信授权后
        if (isset($_GET['state']) && $_GET['state'] == 'wxAuth' && isset($_GET['code'])) {
	        if ($this->isLogin()==false){
                $this->authBack();
            }
        } else {
            if (\Util\Config::get('env','Env') == 'dev') {
                $this->user_id = 1;
                $this->openid = 'oovGB1VGhdmaYoJJVEtV4sTdx9w8';
                $this->nickname = '孔令茂';
                $this->headimgurl = 'http://wx.qlogo.cn/mmopen/ajNVdqHZLLAibuptDCVQfLyszjicsAfuvbWG7G23Bbl0rYvtIibh9Xtrq4QzWQlQQgbcSOZ2u62Cld7Wo6Cjib45NHrTQ3nxhexv4hOCKdFTDQo/0';
            } else {
                if($this->isLogin() == false ) {
			        $this->setUserInfo();
                } else {
                    $this->getUserInfo();
                }
            }
        }
        parent::__construct($request, $response, $invokeArgs);
    }
    private function authBack()
    {
        $code = $_GET['code'];
        $appId = \Util\Config::get('weixin_appid','Env');
        $appSecret = \Util\Config::get('weixin_appsecret','Env');
        $get_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code=$code&grant_type=authorization_code";
        $token_url = $this->http_get($get_token_url);
        $token_url = json_decode($token_url,true);

        $refresh_token = $token_url["refresh_token"];
        $access_token = $token_url["access_token"];
        $openid = $token_url["openid"];
	$info = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
        $user_info = $this->http_get($info);
        $user_info = json_decode($user_info,true);
        if ($user_info) {
            $user = new \Base\Rest();
            $post_data = array(
                'openid'=>$user_info['openid'],
                'nickname'=>$user_info['nickname'],
                'headimgurl'=>$user_info['headimgurl'],
                'sex'=>$user_info['sex'],
                'city'=>$user_info['city'],
                'province'=>$user_info['province'],
                'country'=>$user_info['country'],
            );

            $req= array();
            $post = array('payload'=>base64_encode(http_build_query($post_data)));
            $rest_res = $user->post('User',$req,$post);
            if ($rest_res->isSuccess()) {
                $wei_xin_info = $rest_res->getResponse();
                $this->object2array($wei_xin_info);
                if ($wei_xin_info) {
                    $this->login($wei_xin_info['id'],$wei_xin_info['openid'],$wei_xin_info['nickname'],$wei_xin_info['headimgurl']);
                } else {
                    exit('服务器内部错误code[1]');
                }
            } else {
                exit('服务器内部错误code[2]');
            }

        }else{
            exit('服务器内部错误code[3]');
        }
    }
    public function http_get($url)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }
    private function isLogin()
    {
        $user_session = new Zend_Session_Namespace($this->session_space);
        return (isset($user_session->is_login) && $user_session->is_login == true);
    }
    private function login($user_id,$open_id,$nickname,$headimgurl)
    {
        $user_session = new Zend_Session_Namespace($this->session_space);
        $user_session->user_id = $user_id;
        $user_session->openid = $open_id;
        $user_session->nickname = $nickname;
        $user_session->headimgurl = $headimgurl;
        $user_session->is_login = 1;
        $user_session->setExpirationSeconds(12*60*60); //1天效期（微信信息同步）12*60*
        $this->getUserInfo();
    }
    private function getUserInfo()
    {
        $user_session = new Zend_Session_Namespace($this->session_space);
        $this->user_id = $user_session->user_id;
        $this->openid = $user_session->openid;
        $this->nickname = $user_session->nickname;
        $this->headimgurl = $user_session->headimgurl;
        $this->is_login = $user_session->is_login;
    }
    private function setUserInfo()
    {
        $appId = \Util\Config::get('weixin_appid','Env');
        $appSecret = \Util\Config::get('weixin_appsecret','Env');
        $weixin_model = new Jsapipay();
        $config = array();
        $access_token = $weixin_model->gettoken($appId,$appSecret);
        $config['APPID'] = $appId;
        $config['APPSECRET'] = $appSecret;
        $openid = $weixin_model->GetOpenid($config);
	$rest = new \Base\Rest();
        $req = array(
            'openid' => $openid,
        );
        $res = $rest->get('User',false,$req);
	if ($res->isSuccess()) {
            $old_weixin_info = $res->getResponse();
            $this->object2array($old_weixin_info);
            if ($old_weixin_info) {
                $this->login($old_weixin_info['id'],$old_weixin_info['openid'],$old_weixin_info['nickname'],$old_weixin_info['headimgurl']);

                // 判断微信资料是否跟新过，如有更新更新数据库
                $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
                $lastest_info = $this->http_get($get_user_info_url);
                $lastest_info = json_decode($lastest_info,true);
                if(array_key_exists('nickname',$lastest_info)){ // 查询是否关注
                    if ($lastest_info['nickname'] != $old_weixin_info['nickname'] || $lastest_info['headimgurl'] != $old_weixin_info['headimgurl']) {
                        $user = new \Base\Rest();
                        $post_data = array(
                            'openid'=>$lastest_info['openid'],
                            'nickname'=>$lastest_info['nickname'],
                            'headimgurl'=>$lastest_info['headimgurl'],
                            'sex'=>$lastest_info['sex'],
                            'city'=>$lastest_info['city'],
                            'province'=>$lastest_info['province'],
                            'country'=>$lastest_info['country'],
                        );
                        $req= array();
                        $post = array('payload'=>base64_encode(http_build_query($post_data)));
                        $rest_res = $user->Put('User',$old_weixin_info['id'],$req,$post);
                        if ($rest_res->isSuccess()) {
                            $new_weixin_info = $rest_res->getResponse();
                            $this->object2array($new_weixin_info);
                            if ($new_weixin_info) {
                                $this->login($new_weixin_info['id'],$new_weixin_info['openid'],$new_weixin_info['nickname'],$new_weixin_info['headimgurl']);
                            } else {
                                exit('服务器内部错误code[11]');
                            }
                        } else {
                            exit('服务器内部错误code[12]');
                        }
                    }
                }
            }else{
                // 获取openid 存入数据库
                $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
                $userinfo = $this->http_get($get_user_info_url);
                $user_info = json_decode($userinfo,true);
                if(array_key_exists('nickname',$user_info)){ // 查询是否关注
                    $user = new \Base\Rest();
                    $post_data = array(
                        'openid'=>$user_info['openid'],
                        'nickname'=>$user_info['nickname'],
                        'headimgurl'=>$user_info['headimgurl'],
                        'sex'=>$user_info['sex'],
                        'city'=>$user_info['city'],
                        'province'=>$user_info['province'],
                        'country'=>$user_info['country'],
                    );
                    $req= array();
                    $post = array('payload'=>base64_encode(http_build_query($post_data)));
                    $rest_res = $user->post('User',$req,$post);
                    if ($rest_res->isSuccess()) {
                        $wei_xin_info = $rest_res->getResponse();
                        $this->object2array($wei_xin_info);
                        if ($wei_xin_info) {
                            $this->login($wei_xin_info['id'],$wei_xin_info['openid'],$wei_xin_info['nickname'],$wei_xin_info['headimgurl']);
                        } else {
                            exit('服务器内部错误code[1]');
                        }
                    } else {
                        exit('服务器内部错误code[2]');
                    }
                }else {// 查询是否关注
                    $this->lanchAuth();
                }
            }
        } else {
            exit('服务器内部错误code[5]');
        }
    }
    private function lanchAuth()
    {
        $appId = \Util\Config::get('weixin_appid','Env');
        $back_url = $this->getBackUrl();
        $get_code_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appId&redirect_uri=$back_url&response_type=code&scope=snsapi_userinfo&state=wxAuth#wechat_redirect";
	Header("Location: $get_code_url");
        exit;
    }
    final function object2array($object)
    {
        $object = json_decode(json_encode($object), true);
        return $object;
    }
    private function getBackUrl()
    {
        $request_url = $_SERVER['REQUEST_URI'];
        $domain = \Util\Config::get('weixin_domain','Env');
        $url = (strpos($domain,'http') == false) ? 'http://'.$domain : $domain;

	$tmp_url = parse_url($url.$request_url);
	$request_url = $tmp_url['path'] ?? '' ;
	return $url.$request_url;
    }
    final function uidEncrypt($id)
    {
        return base64_encode(base64_encode($id));
    }
    final function uidDecrypt($encrypt)
    {
        return base64_decode(base64_decode($encrypt));
    }
    public function isSubscribe()
    {
        $appId = \Util\Config::get('weixin_appid','Env');
        $appSecret = \Util\Config::get('weixin_appsecret','Env');
        $weixin_model = new Jsapipay();
        $access_token = $weixin_model->gettoken($appId,$appSecret);
        $openid = $this->openid;

        $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
        $userinfo = $this->http_get($get_user_info_url);
        $userinfo = json_decode($userinfo);
        return $userinfo->subscribe;
    }
    function is_weixin()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }
}
